import {service} from '@/utils/request'
// 把对localstorage的操作封装方法
// 比较优雅的方式是只把token存到缓存里，其他信息比如用户名手机号等通过接口调用获取。
// 但是实际项目中由于后端不给力只能自己把手机号也存到缓存
function getToken(){
    return localStorage.getItem('manage_token')
}
function setToken(val){
    localStorage.manage_token = val
}
function removeToken(){
    localStorage.removeItem('manage_token')
}
function getMobile(){
    return localStorage.getItem('manage_mobile')
}
function setMobile(val){
    localStorage.manage_mobile = val
}
function removeMobile(){
    localStorage.removeItem('manage_mobile')
}
const states = {
    token: getToken(),
    userInfo: ''
}
const mutations = {
    SET_TOKEN: (state, val) => {
        state.token = val
        setToken(val)
    },
    SET_INFO: (state, val) => {
        state.userInfo = val
        setMobile(val.mobile)
    },
    LOGOUT: (state) => {
        state.token = ''
        state.userInfo = ''
        removeMobile()
        removeToken()
    },
}
const actions = {
    // 设置token
    setToken({ commit }, token) {
        commit('SET_TOKEN', token)
    },
    setUserInfo({ commit }, data) {
        commit('SET_INFO', data)
    },
    logout({commit}) {
        commit('LOGOUT')
    },
    getInfo({commit}) {
        return new Promise((resolve, reject) => {
            // 请求接口 获取用户信息
            // 其实应该用token去获取但是根据接口文档参数得是手机号
            const mobile = getMobile()
            if (!mobile){
                reject(new Error('未登录'))
                return
            }
            // 当开发环境时，刷新不请求接口
            if (process.env.NODE_ENV === 'development') {
                commit('SET_INFO', { mobile: mobile})
                resolve()
                return
            }
            // 下面代码仅仅保留为了提醒正常的情况每次刷新都是要请求接口判断用户的权限等
            service.post('/platform-user/partner/partnerDetails',{mobile}, {
                isNoTip: false,
                isNoLoading: true
            }).then(res => {
                commit('SET_INFO', res)
                resolve()
            }).catch(err=>{
                reject(err)
            })
        })
    },
}
export default {
    namespaced: true,
    state: states,
    mutations,
    actions
}